package com.xmhmyh.generalframework.common.conversion;

import com.xmhmyh.generalframework.common.SFunction;
import com.xmhmyh.generalframework.common.utils.MyBeanUtils;
import com.xmhmyh.generalframework.common.vo.SelectVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.lang.reflect.Field;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author: 于丁
 * 实体类转换成前端select格式
 * @DateTime: 2019/12/30 6:06 下午
 */
@Slf4j
public class Bean2SelectConverter {


    public static <T> List<SelectVO> converter(Collection<T> tList, SFunction<T> labelfn, SFunction<T> codefn) {
        try {
            String label = MyBeanUtils.convertToFieldName(labelfn);
            String code = MyBeanUtils.convertToFieldName(codefn);
            if (StringUtils.isBlank(label)) {
                throw new Exception("label为空");
            }
            if (StringUtils.isBlank(code)) {
                throw new Exception("code为空");
            }
            List<SelectVO> selectVOList = tList.stream().map(o -> {
                String labelStr = null;
                String codeStr = null;
                try {
                    Field LabelField = o.getClass().getDeclaredField(label);
                    LabelField.setAccessible(true);
                    Field CodeField = o.getClass().getDeclaredField(code);
                    CodeField.setAccessible(true);
                    labelStr = String.valueOf(LabelField.get(o));
                    codeStr = String.valueOf(CodeField.get(o));
                } catch (NoSuchFieldException | IllegalAccessException e) {
                    log.error("Entity2SelectConverter转换错误={}", label + "不存在");
                }
                return new SelectVO(labelStr, codeStr);
            }).collect(Collectors.toList());
            return selectVOList;
        } catch (Exception e) {
            log.error("Entity2SelectConverter转换错误={}", e.getMessage());
        }
        return null;
    }
}
